package controller;

import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import entity.Reply;
import entity.Topic;
import entity.Users;
import service.IReplyService;
import service.impl.ReplyService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class ReplyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        HttpSession session=request.getSession();
        SmartUpload sm=new SmartUpload();
        sm.initialize(this.getServletConfig(),request,response);
        sm.setCharset("UTF-8");
        try {
            sm.upload();
            sm.save("fil");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        Request srt=sm.getRequest();
        Integer hid= Integer.valueOf(request.getParameter("wid"));
        Users user= (Users) session.getAttribute("user");
        int id= user.getUid();
        String mcontent=srt.getParameter("mcontent");
        String pic=sm.getFiles().getFile(0).getFileName();
        Reply r=new Reply(mcontent,pic,new Users(id),new Topic(hid));
        IReplyService ipd=new ReplyService();

        int b=ipd.addReply(r);

        if (b>0){


            out.print("<script>alert('添加成功');location.href='pag';</script>");
        }else {
            out.print("<script>alert('添加失败');location.href='pag';</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
